// web/src/hooks/useWebSocket.ts
import { useEffect, useState } from 'react';

// @ts-ignore
const useWebSocket = (url) => {
    const [messages, setMessages] = useState([]);
    const [ws, setWs] = useState(null);

    useEffect(() => {
        const socket = new WebSocket(url);
        // @ts-ignore
        setWs(socket);

        socket.onmessage = (event) => {
            // @ts-ignore
            setMessages((prevMessages) => [...prevMessages, event.data]);
        };

        return () => {
            socket.close();
        };
    }, [url]);

    // @ts-ignore
    const sendMessage = (message) => {
        if (ws) {
            // @ts-ignore
            ws.send(message);
        }
    };

    return { messages, sendMessage };
};

export default useWebSocket